#!/usr/bin/env python
# -*- coding: utf-8 -*-

import datetime
import json

from flask import Module, Response, request, flash, jsonify, g, current_app,\
    abort, redirect, url_for, session, Blueprint, render_template

from werkzeug import secure_filename

from planet.post import backend, frontend
from planet.post.forms import PostForm
from planet.post.models import Post
from planet.extensions import db, cache, photos
from planet.helpers import save_image


@backend.route("/", methods=["GET", "POST"])
def index():
    page = int(request.args.get('p', 1))
    posts = Post.query.paginate(page, per_page=50)
    return render_template("post/index.html", page_obj=posts)


@backend.route("/create/", methods=["GET", "POST"])
def new():
    form = PostForm()
    if form.validate_on_submit():
        post = Post()
        # if form.thumb_image.data:
        #     thumb = save_image(form.thumb_image.data)
        #     form.thumb_image.data = json.dumps(thumb)
        form.populate_obj(post)
        # post._thumb = form.thumb_image.data
        db.session.add(post)
        db.session.commit()
        flash("Posting success", "success")
        next_url = url_for('post_backend.edit', id=post.id)
        return redirect(next_url)
    return render_template("post/new.html", form=form)


@backend.route("/<int:id>/edit/", methods=["GET", "POST"])
def edit(id):
    post = Post.query.get_or_404(id)
    form = PostForm(title=post.title, body=post.body)
    if form.validate_on_submit():
        if form.thumb_image.data:
            thumb = save_image(form.thumb_image.data)
            form.thumb_image.data = json.dumps(thumb)
        else:
            form.thumb_image.data = post._thumb
        form.populate_obj(post)
        post._thumb = form.thumb_image.data
        db.session.add(post)
        db.session.commit()
        flash("Posting success", "success")
        next_url = url_for('post_backend.edit', id=post.id)
        return redirect(next_url)
    return render_template("post/edit.html", form=form, post=post)


@frontend.route("/<int:id>", methods=["GET", "POST"])
def view(id):
    post = Post.query.get_or_404(id)
    return render_template("post/view.html", post=post)
